package com.bjpowernode.crm.workbench.web.controller;

import com.bjpowernode.crm.settings.commons.constant.Constants;
import com.bjpowernode.crm.settings.commons.domain.ReturnObject;
import com.bjpowernode.crm.settings.commons.utils.DateUtils;
import com.bjpowernode.crm.settings.commons.utils.HSSFUtils;
import com.bjpowernode.crm.settings.commons.utils.UUIDUtils;
import com.bjpowernode.crm.settings.domain.User;
import com.bjpowernode.crm.settings.service.UserService;
import com.bjpowernode.crm.workbench.domain.Activity;
import com.bjpowernode.crm.workbench.domain.ActivityRemark;
import com.bjpowernode.crm.workbench.service.ActivityRemarkService;
import com.bjpowernode.crm.workbench.service.ActivityService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

@Controller
public class ActivityController {

    @Autowired
    private UserService userService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private ActivityRemarkService activityRemarkService;

    @RequestMapping("/workbench/activity/index.do")
    public String index(HttpServletRequest request) {
        //调用service层的方法
        List<User> userList = userService.queryAllUser();
        //把数据保存到request中
        request.setAttribute("userList", userList);
        //请求转发到市场活动主页面
        return "workbench/activity/index";
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/saveCreateActivity.do")
    public Object saveCreateActivity(Activity activity, HttpSession session) {
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        //封装参数
        activity.setId(UUIDUtils.getUUID());
        activity.setCreateTime(DateUtils.formatDateTime(new Date()));
        activity.setCreateBy(user.getId());//账号有可能改变
        ReturnObject returnObject = new ReturnObject();

        try {
            //调用service层的方法，保存创建的市场活动
            int ret = activityService.saveCreateActivity(activity);
            if (ret > 0) {
                returnObject.setCode(Constants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("添加成功");
            } else {
                returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙,请稍后重试......");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙,请稍后重试......");
        }
        return returnObject;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/queryActivityByConditionForPage.do")
    public Object queryActivityByConditionForPage(String name, String owner, String startDate, String endDate, int pageNo, int pageSize) {
        //封装参数
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("owner", owner);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("beginNo", (pageNo - 1) * pageSize);
        map.put("pageSize", pageSize);
        //调用service层方法，查询数据
        List<Activity> activityList = activityService.queryActivityByConditionForPage(map);
        int totalRows = activityService.queryCountOfActivityByConditionForPage(map);
        //根据查询结果，生成相响应信息
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("activityList", activityList);
        retMap.put("totalRows", totalRows);
        return retMap;
    }

    @ResponseBody  //返回json字符串,ajax请求
    @RequestMapping("/workbench/activity/deleteActivityIds.do")
    public Object deleteActivityIds(String[] id) {//方法名随便写见名知意,并且参数与前端页面传过来的数据名称一样
        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层方法,删除市场活动
            int ret = activityService.deleteActivityByIds(id);
            if (ret > 0) {
                returnObject.setCode(Constants.RETURN_OBJECT_CODE_SUCCESS);
            } else {
                returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统繁忙,,,,请稍后重试,,,");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统繁忙,,,,请稍后重试,,,");
        }
        return returnObject;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/queryActivityById.do")
    public Object queryActivityById(String id) {
        //调用service方法,查询市场活动
        Activity activity = activityService.queryActivityById(id);
        //根据查询结果返回响应信息
        System.out.println(activity);
        return activity;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/saveEditActivity.do")
    public Object saveEditActivity(Activity activity, HttpSession session) {
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        //进一步封装参数
        activity.setEditTime(DateUtils.formatDateTime(new Date()));
        activity.setEditBy(user.getId());//这里不使用name是因为不稳定,用户可能会改名字,用id确保唯一值
        System.out.println(activity);
        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层的方法,保存修改的市场活动
            int ret = activityService.saveEditActivity(activity);
            if (ret > 0) {
                returnObject.setCode(Constants.RETURN_OBJECT_CODE_SUCCESS);
            } else {
                returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统异常请稍后重试.....");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统繁忙,请稍后....");
        }
        return returnObject;
    }

    @RequestMapping("/workbench/activity/fileDownload.do")
    public void fileDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.设置响应信息,在tomcat9之前,要加以下代码，tomcat10就不需要了
        response.setContentType("application/octet-stream;charset=UTF-8");
        //2.获取输出流
        //PrintWriter out = response.getWriter();--这是字符输出流
        OutputStream out = response.getOutputStream();//字节输出流--octet-stream

        //浏览器在接受到响应信息之后，默认情况下，直接在显示窗口中打开响应信息，即使不打开，也会调用程序打开,只有实在打不开才会激活文件下载
        //可以设置响应头信息，使浏览器接收到响应信息之后，直接激活文件下载窗口，即使能打开也不打开
        response.addHeader("Content-Disposition", "attachment;filename=mystudentList.xls");

        //读取excel文件(inputstream),将其输出到浏览器
        InputStream is = null;
        try {
            is = new FileInputStream("D:\\course16(CRM)\\crmproject\\CRM\\serverDir\\studentList.xls");
            byte[] bytes = new byte[1024];
            int count = 0;
            while ((count = is.read(bytes)) != -1) {
                out.write(bytes, 0, count);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            is.close();
            //out是tomcat创建的对象,不是自己new的就不用关
        }
    }

    @RequestMapping("/workbench/activity/exportAllActivities.do")
    public void exportAllActivities(HttpServletResponse response) throws IOException {
        //调用service层的方法,查询所有的市场活动
        List<Activity> activityList = activityService.queryAllActivities();
        //创建exel文件，并且把activityList写入到excel文件中
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("市场活动列表");
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("ID");
        cell = row.createCell(1);
        cell.setCellValue("所有者");
        cell = row.createCell(2);
        cell.setCellValue("名称");
        cell = row.createCell(3);
        cell.setCellValue("开始日期");
        cell = row.createCell(4);
        cell.setCellValue("结束日期");
        cell = row.createCell(5);
        cell.setCellValue("成本");
        cell = row.createCell(6);
        cell.setCellValue("描述");
        cell = row.createCell(7);
        cell.setCellValue("创建时间");
        cell = row.createCell(8);
        cell.setCellValue("创建者");
        cell = row.createCell(9);
        cell.setCellValue("修改时间");
        cell = row.createCell(10);
        cell.setCellValue("修改者");

        //遍历activityList，创建HSSFRow对象，生成所有的数据行
        if (activityList != null && activityList.size() > 0) {
            Activity activity = null;
            for (int i = 0; i < activityList.size(); i++) {
                activity = activityList.get(i);

                //每遍历出一个activity，生成一行
                row = sheet.createRow(i + 1);
                //每一行创建11列，每一列的数据从activity中获取
                cell = row.createCell(0);
                cell.setCellValue(activity.getId());
                cell = row.createCell(1);
                cell.setCellValue(activity.getOwner());
                cell = row.createCell(2);
                cell.setCellValue(activity.getName());
                cell = row.createCell(3);
                cell.setCellValue(activity.getStartDate());
                cell = row.createCell(4);
                cell.setCellValue(activity.getEndDate());
                cell = row.createCell(5);
                cell.setCellValue(activity.getCost());
                cell = row.createCell(6);
                cell.setCellValue(activity.getDescription());
                cell = row.createCell(7);
                cell.setCellValue(activity.getCreateTime());
                cell = row.createCell(8);
                cell.setCellValue(activity.getCreateBy());
                cell = row.createCell(9);
                cell.setCellValue(activity.getEditTime());
                cell = row.createCell(10);
                cell.setCellValue(activity.getEditBy());
            }
        }
        /*//根据wb对象生成excel文件
        OutputStream  out=new FileOutputStream("D:\\course16(CRM)\\crmproject\\CRM\\serverDir\\activities.xls");
        wb.write(out);
        out.close();
        wb.close();

        //把生成的excel文件下载到客户端
        response.setContentType("text/html;charset=utf-8");
        response.addHeader("Content-Disposition","attachment;filename=activityList.xls");
        InputStream is=null;
        OutputStream os = response.getOutputStream();
        try {
            is=new FileInputStream("D:\\course16(CRM)\\crmproject\\CRM\\serverDir\\activities.xls");
            int count=0;
            byte[] bytes=new byte[256];
            while ((count=is.read(bytes))!=-1){
                os.write(bytes,0,count);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            is.close();
            os.close();
        }*/
        //对文件读写进行优化,不直接将内存中的wb文件写到磁盘上,再将磁盘上的文件读取输出到页面上。
        //直接将内存中的wb文件写入到输出流
        response.setContentType("text/html;charset=utf-8");
        response.addHeader("Content-Disposition","attachment;filename=activityList.xls");
        OutputStream os = response.getOutputStream();

        wb.write(os);
        wb.close();
        os.flush();
    }

    /**
     * 配置springmvc的文件上传解析器
     * @param name
     * @param myFile
     * @return
     */
    @ResponseBody
    @RequestMapping("/workbench/activity/fileUpLoad.do")
    public Object fileUpLoad(String name, MultipartFile myFile) throws IOException {
        System.out.println("基尼太美"+name);
        //把文件在服务器指定的目录中生成一个同样的文件
        String originalFilename=myFile.getOriginalFilename();
        File file=new File("D:\\course16(CRM)\\crmproject\\CRM\\serverDir\\",originalFilename);//路径必须手动创建好,文件如果不存在,会自动创建
        myFile.transferTo(file);

        //返回响应信息
        ReturnObject returnObject=new ReturnObject();
        returnObject.setCode(Constants.RETURN_OBJECT_CODE_SUCCESS);
        returnObject.setMessage("上传成功");
        return returnObject;
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/importActivity.do")
    public Object importActivity(MultipartFile activityFile,HttpSession session,String userName){
        User user= (User) session.getAttribute(Constants.SESSION_USER);
        ReturnObject returnObject=new ReturnObject();
        try {
            /*//把接收到的excel文件写道磁盘目录中
            String originalFilename = activityFile.getOriginalFilename();
            File file = new File("D:\\course16(CRM)\\crmproject\\CRM\\serverDir\\", originalFilename);//路径必须手动创建好,文件如果不存在,会自动创建
            activityFile.transferTo(file);
            //解析excel文件,获取文件中的数据,并封装成activityList
            InputStream is=new FileInputStream("D:\\course16(CRM)\\crmproject\\CRM\\serverDir\\"+ originalFilename);
            */
            InputStream is=activityFile.getInputStream();
            HSSFWorkbook wb=new HSSFWorkbook(is);//获取excel文件对象,封装了所有excel文件信息
            HSSFSheet sheet=wb.getSheetAt(0);//获取excel文件第一页

            HSSFRow row=null;//行
            HSSFCell cell=null;//列
            Activity activity=null;//实体类
            List<Activity> activityList=new ArrayList<>();
            for (int i=1;i<=sheet.getLastRowNum();i++){//sheet.getLastRowNum()：最后一行的下标
                row=sheet.getRow(i);//获取得到每一行
                activity=new Activity();
                activity.setId(UUIDUtils.getUUID());//必须设置id唯一性,前台不能让用户自己设置id,
                activity.setOwner(user.getId());
                activity.setCreateTime(DateUtils.formatDateTime(new Date()));
                activity.setCreateBy(user.getId());
                for (int j = 0; j <row.getLastCellNum(); j++) {//row.getLastCellNum(),最后一行下标+1
                    //根据row对象获取HSSCell对象,封装了一列的所有信息
                    cell=row.getCell(j);//获取得到每一列
                    //获取列中的数据
                    String cellValue=HSSFUtils.getCellValueForStr(cell);
                    if (j==0){
                        activity.setName(cellValue);
                    }else if (j==1){
                        activity.setStartDate(cellValue);
                    }else if(j==2){
                        activity.setEndDate(cellValue);
                    }else if(j==3){
                        activity.setCost(cellValue);
                    }else if(j==4){
                        activity.setDescription(cellValue);
                    }
                }
                //每一行中所有的列都封装好之后,保存到list集合当中
                activityList.add(activity);
            }
            //把封装好的数据持久化到磁盘上
            int ret=activityService.saveCreateActivityByList(activityList);
            returnObject.setCode(Constants.RETURN_OBJECT_CODE_SUCCESS);
            returnObject.setRetData(ret);
        }catch (Exception e){
            e.printStackTrace();
            returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统繁忙,请稍后再试......");
        }
        return returnObject;
    }

    @RequestMapping("/workbench/activity/detailActivity.do")
    public String detailActivity(HttpServletRequest request,String id){
        //调用service层查询市场活动
        Activity activity=activityService.queryActivityForDetailById(id);
        List<ActivityRemark> remarkList=activityRemarkService.queryActivityRemarkForDetailByActivityId(id);
        //把数据保存到作用域当中
        request.setAttribute("activity",activity);
        request.setAttribute("remarkList",remarkList);
        System.out.println(activity);
        //跳转到市场活动明细页面
        return "workbench/activity/detail";
    }
}
















